#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

//实现一个自定义的String类，保证main函数对正确执行。实现时，记得采用增量编写的方式，逐一测试。
class String
{
public:
	String()
        : _pstr(new char[1] ()){
        cout << "String()" << endl;
    }

	String(const char *pstr)
        : _pstr(new char[strlen(pstr) + 1] ()){
         cout << "String(const char *pst)" << endl;
        strcpy(_pstr, pstr);
    }

	String(const String &rhs)
        : _pstr(new char[strlen(rhs._pstr) + 1] ()){
        cout << "String(const String &rhs)" << endl;
        strcpy(_pstr, rhs._pstr);
    }

    String &operator=(const String &rhs){
        cout << "String &operator=(const String &rhs)" << endl;
        if(this != &rhs){
            delete [] _pstr;
            _pstr = new char[strlen(rhs._pstr) + 1] ();
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }

    ~String(){
        cout << "~String()" << endl;
        if(_pstr){
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

    void print() const{
        cout << _pstr << endl;
    }

    size_t length() const{
        return strlen(_pstr);
    }

    const char * c_str() const{
        return _pstr;
    }
private:
	char * _pstr;
};

int main()
{
	String str1;
	str1.print();
    cout << str1.length() << endl;	
	

	String str2 = "Hello,world";
	String str3("wangdao");
	
	str2.print();
    cout << str2.length() << endl;		
	str3.print();
    cout << str3.length() << endl;	
	
	String str4 = str3;
	str4.print();
    cout << str4.length() << endl;	
	
	str4 = str2;
	str4.print();
    cout << str4.length() << endl;	

    cout << str4.c_str() << endl;
	
	return 0;
}
